package com.zhkj.txg.module.order.ui.group

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.mine.popup.OrderCouponPopupWindow
import com.zhkj.txg.module.order.adapter.GroupHeaderAdapter
import com.zhkj.txg.module.order.adapter.OrderGroupAdapter
import com.zhkj.txg.module.order.entity.OrderAddressEntity
import com.zhkj.txg.module.order.entity.OrderPayEntity
import com.zhkj.txg.module.order.entity.OrderSubmitEntity
import com.zhkj.txg.module.order.entity.OrderSubmitGroupEntity
import com.zhkj.txg.module.order.popup.PayTypePopupWindow
import com.zhkj.txg.module.order.ui.AddressManagerActivity
import com.zhkj.txg.module.order.vm.OrderViewModel
import com.zhkj.txg.utils.PayUtils
import com.zhkj.txg.utils.WXPayEntity
import kotlinx.android.synthetic.main.activity_order_detail.*
import kotlinx.android.synthetic.main.item_order_address.*
import java.math.BigDecimal

class OrderSubmitGroupActivity : ViewModelActivity<OrderViewModel>() {

    companion object {

        private val GOODS_ID = "goodsId"
        private val SPEC_ID = "specId"
        private val GOODS_NUM = "goodsNum"
        private val GROUP_ID = "groupId"
        private val GROUP_TYPE = "groupType"
        private val SHARE_ID = "shareId"

        private val CART_IDS = "cartIds"

        fun groupBuyNow(
            context: Context,
            goodsId: Int,
            specId: Int,
            goodsNum: Int,
            group_id: Int = 0,
            groupType: Int = 1,
            shareId: Int = 0
        ) {
            val intent = Intent(context, OrderSubmitGroupActivity::class.java)
                .putExtra(GOODS_ID, goodsId).putExtra(SPEC_ID, specId)
                .putExtra(GOODS_NUM, goodsNum).putExtra(SHARE_ID, shareId)
                .putExtra(GROUP_ID, group_id).putExtra(GROUP_TYPE, groupType)
            context.startActivity(intent)
        }

//        fun cartBuy(context: Context, cartIds: String) {
//            val intent = Intent(context, OrderSubmitGroupActivity::class.java).putExtra(TYPE, 1)
//                .putExtra(CART_IDS, cartIds)
//            context.startActivity(intent)
//        }
    }

    private var groupType: Int = 0
    private var group_id: Int = 0
    private var user_note: String = ""

    override val layoutResId: Int = R.layout.activity_order_detail
    override fun setViewModel(): OrderViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleOrder

    //    private val orderAdapter = OrderGroupAdapter()
    private val orderAdapter = OrderGroupAdapter { uiPosition, content -> // 填写备注
        viewModel.orderGroupLiveData.value?.response?.data?.let {
//            it.cartList[uiPosition].orderDesc = content
            if (content != null) {
                user_note = content
            }
        }
    }.apply {
        setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.viewSelectShopCoupon -> { // 选择优惠券
//                    val couponList = data[position].couponList
                    viewModel.orderGroupLiveData.value?.response?.data?.let {
                        val couponList = it.couponList
                        if (couponList.isEmpty()) toast(getString(R.string.shop_coupon_empty))
                        else with(orderCouponPopupWindow) {// 弹出优惠券PopupWindow
                            type =
                                com.zhkj.txg.module.mine.popup.OrderCouponPopupWindow.TYPE_SHOP
                            uiPosition = position
                            setData(couponList)
                            showPopupWindow()
                        }
                    }
                }
            }
        }
    }
    private val headerAdapter = GroupHeaderAdapter()
    private val REQUEST_ADDRESS = 100
    private val payTypePopupWindow: PayTypePopupWindow by lazy {
        PayTypePopupWindow(this, { type, orderInfo ->
            viewModel.groupPayOrder(
                AccountManager.getToken(), 0,
                orderInfo.orderSignNumber, type
            )
        }, { false })
    }

    private val orderCouponPopupWindow: OrderCouponPopupWindow by lazy {
        OrderCouponPopupWindow(this) { type, uiPosition, coupon ->
            // 选中优惠券
            viewModel.orderGroupLiveData.value?.response?.data?.let {
                it.goods?.selectCoupon = coupon
                // 计算金额
                var totalCouponFee = BigDecimal(0)
                if (it.goods?.selectCoupon != null) totalCouponFee =
                    totalCouponFee.add(BigDecimal(it.goods?.selectCoupon!!.money))
                it.goods?.useCouponTotalPrice =
                    BigDecimal(it.goodsTotalFee).subtract(totalCouponFee).toDouble()
                fillData(it, false)
            }
        }
    }

    override fun initViewModel() {
        groupType = intent.getIntExtra(GROUP_TYPE, 1)
        // 订单详情数据观察者
        viewModel.orderGroupLiveData.observe(this, Observer { it ->
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                it.response?.data?.let { fillData(it, true) }
            }
        })
        // 微信支付结果观察者
        viewModel.payResult().observe(this, Observer {
            if (it.paySuccess) {
                // 通知购物车，需要刷新
//                if (intent.getIntExtra(TYPE, 0) == 1) RxBus.post(CartRefreshEvent())
                paySuccess()
            } else toast(it.payDesc)
        })
        // 订单支付信息数据观察者
        viewModel.payOrderLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let { order ->
                if (!order.isNeedPay) {
                    // 通知购物车，需要刷新
//                    if (intent.getIntExtra(TYPE, 0) == 1) RxBus.post(CartRefreshEvent())
                    paySuccess()
                } else when (order.payType) {
                    OrderPayEntity.TYPE_WECHAT -> { // 微信支付
                        order.payInfo.let {
                            PayUtils.wxPay(this, Gson().fromJson(it, WXPayEntity::class.java))
                        }
                    }
                    // 支付宝支付
                    OrderPayEntity.TYPE_ALIPAY -> PayUtils.aliPay(this, order.payInfo, {
                        // 通知购物车，需要刷新
//                        if (intent.getIntExtra(TYPE, 0) == 1) RxBus.post(CartRefreshEvent())
                        paySuccess()
                    }, { toast(it) })
                    else -> Unit
                }
            }
        })
    }

    override fun initUI() {
        if (groupType == 1) {
//            frame_group.visibility = View.VISIBLE
        }
        frame_coupon.visibility = View.GONE
        rvOrder.apply {
            layoutManager = LinearLayoutManager(this@OrderSubmitGroupActivity)
            adapter = orderAdapter
        }
        recycler_view.adapter = headerAdapter
        btnAddress.setOnClickListener {
            AddressManagerActivity.selectAddress(this@OrderSubmitGroupActivity, REQUEST_ADDRESS)
        }
        btnSubmit.setOnClickListener {
            if (viewModel.orderGroupLiveData.value?.response?.data?.address == null) {
                toast(getString(R.string.select_default_address))
                return@setOnClickListener
            }
            viewModel.submitGroupOrder(
                AccountManager.getToken(),
                groupType,
                group_id,
                user_note
            ).takeIf {
                !it.hasObservers()
            }?.observe(this, Observer { it ->
                handlerResponseStatus(it.status, it.statusTip)
                if (it.status == HttpResponseStatus.Status.SUCCESS) {
                    it.response?.data?.let {
                        showPayPopup(it)
                    }
                }
            })
        }
    }

    override fun initData() {
//        when (intent.getIntExtra(TYPE, 0)) {
//            0 -> {
        val goodsId = intent.getIntExtra(GOODS_ID, 0)
        val specId = intent.getIntExtra(SPEC_ID, 0)
        val goodsNum = intent.getIntExtra(GOODS_NUM, 0)
        group_id = intent.getIntExtra(GROUP_ID, 0)
        val shareId = intent.getIntExtra(SHARE_ID, 0)
        viewModel.groupBuyNow(
            AccountManager.getToken(),
            goodsId,
            goodsNum,
            specId,
            group_id,
            groupType,
            shareId
        )
//            }
//            1 -> {
//                viewModel.cartBuy(AccountManager.getToken(), intent.getStringExtra(CART_IDS) ?: "")
//            }
//        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_ADDRESS) {
            val address = data?.getSerializableExtra("data") as OrderAddressEntity
            viewModel.orderGroupLiveData.value?.response?.data?.address = address
            fillAddress(address)
        }
    }

    private fun fillData(order: OrderSubmitGroupEntity, isInit: Boolean) {
        fillAddress(order.address)
//        tvShopCouponName.text = order.selectCoupon?.name ?: ""
        tvTotalCount.text = "共${order.goodsTotalNum}件，合计"
        tvTotalAmount.text = SpanUtil.setMoneySymbol(order.goods?.useCouponTotalPrice.toString())

        if (isInit) orderAdapter.setNewData(mutableListOf(order.goods!!))
        else orderAdapter.notifyDataSetChanged()
        if (isInit) headerAdapter.setNewData(order.groups)
        else headerAdapter.notifyDataSetChanged()
    }

    private fun fillAddress(address: OrderAddressEntity?) {
        if (address != null) {
            tvOrderAddressName.visibility = View.VISIBLE
            tvOrderAddressName.text = address.consignee
            tvOrderAddressMobile.visibility = View.VISIBLE
            tvOrderAddressMobile.text = address.mobile
            tvOrderAddress.text = address.address
        } else {
            tvOrderAddressName.visibility = View.GONE
            tvOrderAddressMobile.visibility = View.GONE
            tvOrderAddress.text = getString(R.string.select_address)
        }
    }

    private fun paySuccess() {
        toast(getString(R.string.pay_success))
        payTypePopupWindow.dismiss()
        GroupOrderListActivity.open(this, 0)
        finish()
    }

    private fun showPayPopup(it: OrderSubmitEntity) {
        payTypePopupWindow.run {
            setData(it)
            showPopupWindow()
        }
    }
}